package com.seguriapp.gwt.client.login;

import net.customware.gwt.dispatch.client.DispatchAsync;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.seguriapp.common.gwt.client.AbstractSeguriAppPresenter;
import com.seguriapp.common.gwt.client.SeguriAppCallback;
import com.seguriapp.common.gwt.client.SeguriAppDisplay;
import com.seguriapp.gwt.shared.ValidateCredentialsAction;
import com.seguriapp.gwt.shared.ValidateCredentialsResult;

public class LoginPanelPresenter extends AbstractSeguriAppPresenter {

  private final Display display;

  public LoginPanelPresenter(final DispatchAsync dispatchAsync, final EventBus eventBus, final PlaceController placeController, final Display display) {
    super(dispatchAsync, eventBus, placeController);
    this.display = display;
    this.display.setPresenter(this);
  }

  public void start() {

  }

  public void validateCredentials(final String username, final String password) {
    final ValidateCredentialsAction action =  new ValidateCredentialsAction();
    action.setUsername(username);
    action.setPassword(password);
    dispatchAsync.execute(action, new SeguriAppCallback<ValidateCredentialsResult>() {

      public void onSuccess(final ValidateCredentialsResult result) {
        if (result.isValid()) {

//          display.cleanFields(true);
//          final SeguriAppClientSession clientSession = SeguriAppClientSession.get();
//          final User user = new User(0L, username, result.isAdministrator(), result.getLastDateLoggedIn(), result.getEntitiesList());
//          clientSession.put(Key.User, user, true);
          display.submitLoginForm();
        } else {
          display.showError(result.getErrorMessage(), true);
          display.cleanFields(false);
        }
      }

      public void onFailure(Throwable e) {
        display.showError("Hubo un error con el sistema, por int\u00e9ntelo en unos minutos.", true);
      }
    });
  }

  public interface Display extends SeguriAppDisplay {

    void setPresenter(LoginPanelPresenter presenter);

    void submitLoginForm();

    void showError(String errorMessage, boolean showError);

    void cleanFields(boolean allFields);
  }

}